import {map_set_tiandimap} from '@/consts';

const noop = () => {};
export interface Options {
  exportGetter?: () => any | undefined;
}

export default function getScriptAsync({ exportGetter = noop }: Options): Promise<any> {
  return new Promise(async (resl, rej) => {
    if ((window as any).T?.Map) { return resl(exportGetter()) }

    await new Promise(async (resl1, rej1) => {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `http://api.tianditu.gov.cn/api?v=4.0&tk=${await map_set_tiandimap.value.__getValue('browser_ak_limit_no')}`;
      script.onload = () => {
        resl1(0)
      };
      script.onerror = () => rej1(new Error('script load error'));
      document.body.appendChild(script);
      const styl = document.createElement('style');
      styl.innerHTML = `.tmap-autocomplete{position:fixed;z-index:9999;max-height:300px;min-width:300px;overflow:auto;display:none;}
      .tmap-autocomplete__item{cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding:2px 5px;background:#eee;color:#212121;line-height:1.5;}
      .tmap-autocomplete__item:not(:last-child){border-bottom:1px solid #ddd;}
      .tmap-autocomplete__item:hover{background:#bbb;}`;
      document.head.appendChild(styl);
    });

    resl(exportGetter());
  })
}